package com.jzy.bxb.core.db.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jzy.bxb.core.util.FileUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Redis
 *
 * @author JiangZhiYong
 * @date 2017-04-14 QQ:359135103
 */
public class AbsRedisManager {
	private static final Logger log = LoggerFactory.getLogger(AbsRedisManager.class);
	protected JedisPool pool = null;
	protected RedisConfig redisConfig;

	protected AbsRedisManager(String configPath) {
		super();
		this.redisConfig = FileUtil.getConfigXML(configPath, "redisConfig.xml", RedisConfig.class);
		if (this.redisConfig == null) {
			throw new RuntimeException(String.format("redis配置文件%s不存在", configPath));
		}
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.setMaxIdle(redisConfig.getMaxIdle());
		jedisPoolConfig.setMaxTotal(redisConfig.getMaxTotal());
		jedisPoolConfig.setTestOnBorrow(redisConfig.isTestOnBorrow());
		jedisPoolConfig.setMaxWaitMillis(redisConfig.getMaxWaitMillis());
		pool = new JedisPool(jedisPoolConfig, redisConfig.getIp(), redisConfig.getPort(), redisConfig.getTimeOut(),
				redisConfig.getPassword());
	}

	public Jedis getClient() {
		if (pool == null) {
			return null;
		}
		Jedis client = pool.getResource();
		return client;
	}

	@SuppressWarnings("deprecation")
	public void returnClient(Jedis jedis) {
		pool.returnResource(jedis);
	}

	/**
	 * 释放jedis资源
	 * 
	 * @param jedis
	 */
	public static void closeResource(final Jedis jedis) {
		if (jedis != null) {
			jedis.close();
		}
	}

	public void shutDownPool() {
		if (pool != null) {
			log.info("redis pool is shutdown...");
			pool.destroy();
		}
	}

}
